package com.atguigu.controller;

import com.atguigu.base.BaseController;
import com.atguigu.entity.Admin;
import com.atguigu.entity.HouseBroker;
import com.atguigu.service.AdminService;
import com.atguigu.service.HouseBrokerService;
import com.atguigu.service.Roleservice;
import com.atguigu.util.QiniuUtil;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {
    @DubboReference
    private AdminService adminService;
    @DubboReference
    private HouseBrokerService houseBrokerService;
    @DubboReference
    private Roleservice roleservice;
    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 分页带条件查询用户信息的处理器
     */
    @RequestMapping
    public String index(ModelMap map, HttpServletRequest request){
        //接收用户发过来查询条件个分页信息（username name phone createTimeBegin ）
        Map<String, Object> filters = getFilters(request);
        //调用服务层方法，获取pageInfo 对象
        PageInfo<Admin> page = adminService.findPage(filters);
        //将pageInfo对象放入请求域
        map.addAttribute("page",page);
        //将用户填写信息页放入请求域进行回显
        map.put("filters",filters);
        //渲染视图admin/index
        return "admin/index";
    }
    @RequestMapping("/create")
    public String create(){
        return "admin/create";
    }
    /**
     * 保存员工信息进入数据库处理器
     * 存储完毕后要渲染一个成功页
     */
@PostMapping("/save")
    public String save(Admin admin){
    //设置默认头像
    admin.setHeadUrl("http://47.93.148.192:8080/group1/M00/03/F0/rBHu8mHqbpSAU0jVAAAgiJmKg0o148.jpg");
    String encode = passwordEncoder.encode(admin.getPassword());
    admin.setPassword(encode);
    //接收表单提交的信息
    adminService.index(admin);
    return "common/successPage";
}

@RequestMapping("/edit/{id}")
    public String edit(ModelMap modelMap,@PathVariable("id") Long id){
    Admin admin = adminService.getById(id);
    modelMap.addAttribute("admin",admin);
    return "admin/edit";
}

@RequestMapping("update")
    public String update(Admin admin){
    Integer update = adminService.update(admin);

    return "common/successPage";
}

/*
* 接收占位符方式参数 用户id
* 根据id删除用户
* 重新渲染用户信息展示页
* */
@RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") Long id){
    adminService.delete(id);
    return "redirect:/admin";
}

@RequestMapping("/uploadShow/{id}")
public String uploadshow(@PathVariable Long id,ModelMap modelMap){
    modelMap.addAttribute("id",id);
    return "admin/upload";
}
@RequestMapping("/upload/{id}")
    public String upload(@PathVariable Long id,
                         @RequestParam("file")MultipartFile multipartFile) throws IOException {
    String filename = UUID.randomUUID().toString();
    QiniuUtil.upload2Qiniu(multipartFile.getBytes(),filename);
    String url ="http://rkfwfy8ib.hn-bkt.clouddn.com/"+filename;
    Admin admin = new Admin();
    admin.setId(id);
    admin.setHeadUrl(url);
    adminService.update(admin);
    //同步更新房产经纪人的头像
    HouseBroker houseBroker = new HouseBroker();
    houseBroker.setBrokerId(id);
    houseBroker.setBrokerHeadUrl(url);
    houseBrokerService.updateBrokerHeadImgUrl(houseBroker);
    return "common/successPage";
}
    @GetMapping("/assignShow/{id}")
    public String assignShow(@PathVariable("id")Long id, Model model){
        Map<String,Object> rolemap = roleservice.findRoleByAdminId(id);
        model.addAllAttributes(rolemap);
        model.addAttribute("adminId",id);
        return "admin/assignShow";
    }
    @PostMapping("/assignRole")
    public String saveUserRole(Long adminId,Long[] roleIds){
    roleservice.saveUserRoleRealtionShip(adminId,roleIds);
    return "common/successPage";
    }
    @GetMapping("/getInfo")
    @ResponseBody
    public Object getInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getPrincipal();
    }
}
